﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AB_SD_Entities;
using AB_SD_Commons.Helpers;
using System.Data.SqlClient;
using System.Data;

namespace AB_SD_DataAccess
{
    public static class CountyDAO
    {
        /// <summary>
        /// Select a county by id
        /// </summary>
        /// <param name="countryId"></param>
        /// <returns></returns>
        public static County Select(int id)
        {
            County result = new County();

            string sql = "select * from county where id=@countyid";
            SqlParameter[] sqlparams = new SqlParameter[1];
            sqlparams[0] = new SqlParameter("@countyid", SqlDbType.Int);
            sqlparams[0].Value = id;
            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlparams);

            if (dt != null)
            {
                if (dt.Rows.Count == 1)
                {
                    result.Id = (int)dt.Rows[0]["Id"];
                    result.Name = dt.Rows[0]["Name"].ToString();
                    result.CountryId = (int)dt.Rows[0]["CountryId"];
                    return result;
                }
                else
                    return null;
            }
            else
                return null;
        }

        /// <summary>
        /// Select all towns in a county
        /// </summary>
        /// <param name="countyId">County ID</param>
        /// <returns></returns>
        public static List<Town> SelectAllTowns(int countyId)
        {
            List<Town> result = new List<Town>();

            string sql = "select Town.Id, Town.Name, Town.CountyId "
            + "from (Town join County on Town.CountyId = Town.Id) "
            + "where Town.CountyId = @countyid";

            SqlParameter[] sqlParam = new SqlParameter[1];

            sqlParam[0] = new SqlParameter("@postcode", SqlDbType.Int);
            sqlParam[0].Value = countyId;

            DataTable dt = SqlHelper.ExecuteSelectQuery(sql, sqlParam);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Town town = new Town((int)dt.Rows[i]["Id"], dt.Rows[i]["Name"].ToString(), (int)dt.Rows[i]["CountyId"]);
                        result.Add(town);
                    }
                }
            }
            return result;
        }
    }
}
